import os  # todo：导入系统模块
from BaseDriver.appium_server import start_Appium_server  # todo：引入appium_server方法

def get_project_path():
    # 项目名称
    p_name = 'app_page_object_model'
    # 获取当前文件的绝对路径
    p_path = os.path.abspath(os.path.dirname(__file__))
    # 通过字符串截取方式获取
    return p_path[:p_path.index(p_name) + len(p_name)]

caps_yaml = get_project_path() + os.sep + "Config" + os.sep + "caps.yaml"  # todo：拼接caps_yaml路径

# print(caps_yaml)
# print(os.path.abspath(os.path.dirname(__file__)))
# os.path.abspath(os.path.dirname(__file__))
# p_path = os.path.abspath(os.path.dirname(__file__))
# print(p_path) # E:\app_page_object_model\BaseDriver
# print(p_path[:p_path.index('app_page_object_model') + len('app_page_object_model')]) # E:\app_page_object_model
# print(p_path[:p_path.index('app_page_object_model')]) # E:\
# print(p_path[:p_path.index('app_page_object_model')+ len('app_page_object_model')]) # E:\app_page_object_model

# str1 = "十九期王长帅"
# print(str1[:str1.index('王长帅') + len("王长帅")]) #


def readyaml():  # todo：读取yaml方法
    import yaml
    with open(caps_yaml, 'r', encoding='utf-8') as f:
        value = yaml.load(f, Loader=yaml.FullLoader)  # todo：Loader=yaml.FullLoader忽略警告
    return value



class BaseDriver():  # todo：基类driver
    def __init__(self, deviceDesc):  # todo：初始化方法，传入需要调用的devicename
        self.deviceDesc = deviceDesc  # todo：重新赋值
        for i in readyaml():  # todo：遍历yaml文件
            if i['deviceDesc'] == deviceDesc:  # todo：如果yaml文件中的某个手机名等于我传入的设备名
                self._configdesc = i  # todo：那么我就将所有的手机配置赋值给一个新的变量
                # print(self._configdesc)
                self.desired_caps = i['desired_caps']  # todo：将连接appium的参数单独取出来
                # print(self.desired_caps)

    @staticmethod  # todo：静态方法，不走类方法
    def clear_cache(PackageName):  # todo：清除包的缓存。传入的参数为包名
        os.system('adb shell pm clear' + ' ' + PackageName)  # todo：adb shell pm clear packagename  清除包的缓存

    @staticmethod
    def uninstall_package(PackageName):
        os.system('adb uninstall '+PackageName)  # todo：卸载app

    @staticmethod
    def install_package(apk):
        def get_apk():
            for dir_path, dir_name, file_name in os.walk(get_project_path()):  # 使用os内置方法遍历该路径下的文件路径、文件夹名字、文件名字
                for file in file_name:  # 循环所有的文件名
                    if apk == file:  # 如果传入的apk和文件名对上
                        apk_path = os.path.join(dir_path, file)  # 使用os内置方法进行拼接完整路径
                        return apk_path
        os.system('adb install -r '+str(get_apk()))




    def adb_connect(self):  # todo：adb 连接方法
        device = self.desired_caps['udid']  # todo：寻找设备的udid，udid为安卓设备的唯一标识符
        os.system('adb kill-server')  # todo：为保证测试稳定，先杀死adb server
        os.system('adb start-server')  # todo：再打开adb server
        os.system('adb connect ' + str(device))  # todo： 连接设备，udid就是需要连接

    def base_driver(self):  # todo：实例化driver方法
        from appium import webdriver  # todo：引入appium模块下的webdriver
        self.adb_connect()  # todo：先做连接操作
        self.configdriver = {}  # todo：定义一个连接driver的配置空字典
        self.configdriver['platformVersion'] = self.desired_caps['platformVersion']  # todo：略
        self.configdriver['deviceName'] = self.desired_caps['deviceName']  # todo：略
        self.configdriver['udid'] = self.desired_caps['udid']  # todo：需要写如udid
        self.configdriver['appPackage'] = self.desired_caps['appPackage']  # todo：略
        self.configdriver['appActivity'] = self.desired_caps['appActivity']  # todo：略
        self.configdriver['noReset'] = self.desired_caps['noReset']  # todo：跳过手机引导页，但是不怎么好用
        self.configdriver['platformName'] = self.desired_caps['platformName']  # todo：略
        self.configdriver['automationName'] = self.desired_caps['automationName']  # todo：automationName，用的底层是哪个uiautomation
        self.configdriver['unicodeKeyboard'] = True
        self.url = self._configdesc['server_url']  # todo：appium server的地址
        self.uninstall_package(str(self.desired_caps['appPackage']))  # todo：每次调用driver方法的时候，都先卸载下app
        self.install_package(str('base.apk'))
        start_Appium_server()  # todo：启动appium server，将server挂载到后台运行
        self.driver = webdriver.Remote(str(self.url) + ':' + str(self._configdesc['server_prot']) + '/wd/hub',
                                       self.configdriver)
        # todo：拼接路径，同之前一致：http://localhost:4723/wd/hub
        return self.driver  # todo：返回driver
